package com.youi.web;

import com.youi.common.Common;
import com.youi.common.DelStatus;
import com.youi.common.SessionKey;
import com.youi.entity.Groupleader;
import com.youi.entity.Leaderstore;
import com.youi.entity.User;
import com.youi.entity.Uservip;
import com.youi.entity.Userwechat;
import com.youi.exception.BusinessException;
import com.youi.manage.HttpRequestManage;
import com.youi.manage.HttpSessionManage;
import com.youi.service.GroupleaderService;
import com.youi.service.LeaderfanService;
import com.youi.service.LeaderstoreService;
import com.youi.service.UserService;
import com.youi.service.UservipService;
import com.youi.service.UserwechatService;
import com.youi.third.meiyijiauser.model.MemberResult;
import com.youi.third.wechat.model.BaseObject;
import com.youi.third.wechat.model.EncryptedData;
import com.youi.third.wechat.util.WXCoreUtil;
import com.youi.third.wechat.util.WechatUtil;
import com.youi.util.CommonInfoUtil;
import com.youi.util.IpUtil;
import com.youi.util.JsonUtil;
import com.youi.util.LogUtil;
import com.youi.util.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户信息信息控制层
 *
 * @author Administrator
 */
@Controller
public class UserController extends HttpRequestManage {

    @Autowired
    private UserService userService;
    @Autowired
    private UserwechatService userwechatService;
    @Autowired
    private GroupleaderService groupleaderService;
    @Autowired
    private LeaderstoreService leaderstoreService;
    @Autowired
    private UservipService uservipService;
    @Autowired
    private LeaderfanService leaderfanService;


    /**
     * M-0
     * 微信小程序授权
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     */
    @ResponseBody
    @RequestMapping("weChatMiniLicenseLogin")
    public String weChatMiniLicenseLogin(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) throws BusinessException {
        //授权code
        String code = getString("code", request);
        //头像链接
        String avatarUrl = optString("avatarUrl", request);
        //性别
        String gender = optString("gender", request);
        //昵称
        String nickName = optString("nickName", request);
        //加密算法的初始向量，详见 用户数据的签名验证和加解密
        String iv = getString("iv", request);
        //敏感数据在内的完整用户信息的加密数据
        String encryptedData = getString("encryptedData", request);
        //手机号码
        String phone = optString("phone", request);
        //获取微信基础数据对象
        BaseObject baseObject = WechatUtil.weChatMiniGetBaseObject(code);
        if (baseObject == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLOBJECT, "微信授权失败");
        }
        String result = WXCoreUtil.decrypt(WechatUtil.mini_appid, encryptedData, baseObject.getSession_key(), iv);
        if (result == null && result.length() > 0) {
            return JsonUtil.toJson(CommonInfoUtil.DATAERROR, "敏感数据解密失败");
        }
        EncryptedData data = JsonUtil.fromJson(result, EncryptedData.class);
        String openid = baseObject.getOpenid();
        String unionid = null;
        if (data != null && data.getUnionId() != null) {
            unionid = data.getUnionId();
        }
        Userwechat userother = userwechatService.getUserwechat(WechatUtil.mini_appid, openid, unionid, "1", IpUtil.getIpAddr(request));
        LogUtil.Info("openid=" + openid);
        LogUtil.Info("unionid=" + unionid);
        User user = null;
        /**查询用户信息*/
        if (userother.getUserId() == null) {
            /**查询是否通过其他授权*/
            user = userwechatService.getWeChatLicenseUserId(unionid);
            if (user == null) {
                user = userwechatService.getNewUser(avatarUrl, nickName, gender, phone);
                userService.saveOrUpdate(user);//保存获得userid
            }
        } else {
            user = userService.get(userother.getUserId());
            user.setImg(avatarUrl);
            user.setNickName(nickName);
            user.setGender(getGender(gender));
            Map<String, Object> prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put(Common.USERID, user.getId());
            Uservip uservip = uservipService.getByParam(prams);
            if (uservip != null) {
                uservip.setNickname(nickName);
                uservip.setGender(getGender(gender).toString());
                uservip.setAvatarUrl(avatarUrl);
                if (uservip.getRegisterTime() == null) {
                    uservip.setRegisterTime(new Date());
                }
                uservipService.saveOrUpdate(uservip);
            }
        }
        if (user == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "微信登录失败");
        }
        /**更新信息*/
        String token = MD5.getPwdMd5(new Date().toString() + user.getId());
        user.setToken(token);
        userService.saveOrUpdate(user);
        /**更新用户微信授权信息*/
        userother.setUserId(user.getId());
        userwechatService.saveOrUpdate(userother);
        /**更新同一个unionid的用户关联*/
        userwechatService.updateAllUnion(unionid, user.getId());
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put(Common.USERID, user.getId());
        Groupleader groupleader = groupleaderService.getByParam(prams);
        if (groupleader != null) {
            user.setLeaderId(groupleader.getId());
            prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put("leaderId", groupleader.getId());
            List<Leaderstore> leaderstoreList = leaderstoreService.getByParams(prams);
            for (Leaderstore leaderstore : leaderstoreList) {
                if (leaderstore.getLevel() == 1) {
                    user.setLeaderLevel(1);
                } else if (leaderstore.getLevel() == 2) {
                    user.setLeaderLevel(2);
                }
                break;
            }
//				user.setAuthStore(groupleader.getAuthStore());
//				user.setAuthStoreCode(groupleader.getAuthStoreCode());
        } else {
            user.setLeaderLevel(0);
        }
        /**将用户信息放入session*/
        HttpSessionManage.setAttribute(request, SessionKey.USER, user);
        modelMap.put(Common.TOKEN, user.getToken());
        modelMap.put(Common.OPENID, openid);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", modelMap);
    }

    /**
     * M-1
     * 查询当前登录用户信息
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     */
    @ResponseBody
    @RequestMapping("userGetInfo/getLoginUser")
    public String getLoginUser(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        User user = (User) HttpSessionManage.getAttribute(request, SessionKey.USER);
        if (user == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", user);//jsonObject	json对象
    }

    /**
     * 检测token是否有效
     */
    @ResponseBody
    @RequestMapping("checkToken")
    public String checkToken(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        String token = getString(Common.TOKEN, request);
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put(Common.TOKEN, token);
        User user = userService.getByParam(prams);
        if (user == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");//jsonObject	json对象
    }

    /**
     * M-16
     * 获取手机号码注册会员
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     */
    @ResponseBody
    @RequestMapping("userGetInfo/getPhoneRegMember")
    public String editLoginUserMobile(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        //授权code
        String code = getString("code", request);
        //加密算法的初始向量，详见 用户数据的签名验证和加解密
        String iv = getString("iv", request);
        //敏感数据在内的完整用户信息的加密数据
        String encryptedData = getString("encryptedData", request);
        //用户token
        String token = getString(Common.TOKEN, request);
        //获取微信基础数据对象
        BaseObject baseObject = WechatUtil.weChatMiniGetBaseObject(code);
        if (baseObject == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLOBJECT, "微信授权失败");
        }
        String sensitivitydata = WXCoreUtil.decrypt(WechatUtil.mini_appid, encryptedData, baseObject.getSession_key(), iv);
        if (sensitivitydata == null || sensitivitydata.length() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.DATAERROR, "敏感数据解密失败");
        }
        EncryptedData data = JsonUtil.fromJson(sensitivitydata, EncryptedData.class);
        if (data == null) {
            return JsonUtil.toJson(CommonInfoUtil.DATAERROR, "敏感数据解密失败");
        }
        User user = (User) HttpSessionManage.getAttribute(request, SessionKey.USER);
        if (user == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        user.setPhone(data.getPurePhoneNumber());
        MemberResult memberResult = null;
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put(Common.USERID, user.getId());
        Userwechat userwechat = userwechatService.getByParam(prams);
        uservipService.saveOrUpdate(new Uservip(user.getId(), data.getNickname(), data.getGender(), data.getAvatarUrl(),
                data.getCountry(), data.getProvince(), data.getCity(), null, null, user.getUserNo(), null, null, new Date()));
        user.setIsVip(1);
        userService.saveOrUpdate(user);
        HttpSessionManage.setAttribute(request, SessionKey.USER, user);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");//jsonObject	json对象
    }

    /**
     * 获取顶级佳选官头像
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     */
    @ResponseBody
    @RequestMapping("userGetInfo/getTopLeaderImg")
    public String getTopLeaderImg(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        User user = (User) HttpSessionManage.getAttribute(request, SessionKey.USER);
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("leaderId", user.getLeaderId());
        Leaderstore leaderstore = leaderstoreService.getByParam(prams);
        if (leaderstore == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "团长信息不存在");
        }
        if (leaderstore.getLevel() == 2) {
            prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put("storeId", leaderstore.getStoreId());
            prams.put("level", 1);
            Leaderstore topLeaderstore = leaderstoreService.getByParam(prams);
            if (topLeaderstore != null) {
                prams = new HashMap<String, Object>();
                prams.put(Common.DELSTATUS, DelStatus.NODEL);
                prams.put(Common.ID, leaderstore.getLeaderId());
                Groupleader groupleader = groupleaderService.getByParam(prams);
                if (groupleader != null) {
                    User otherUser = userService.get(groupleader.getId());
                    if (user != null) {
                        modelMap.put("topleaderImg", user.getImg());
                    } else {
                        modelMap.put("topleaderImg", "");
                    }
                }

            }
        } else {
            modelMap.put("topleaderImg", "");
        }
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", modelMap);
    }

    //获取性别
    private Integer getGender(String gender) {
        if (gender.equals("1")) {
            return 2;
        } else if (gender.equals("2")) {
            return 1;
        }
        return 0;
    }

}
